<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        div{
            text-align: center;
        }
        img{
            vertical-align: top;
        }
        div.nav{
            position: fixed;
            top: 0;
            left: 50%;
            transform: translateX(-50%);
        }
        #main{
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div id="top">
        <img src="./top.png" alt="">
    </div>
    <div id="nav">
        <img src="./nav.png" alt="">
    </div>
    <div id="main">
        <img src="./main.png" alt="">
    </div>
</body>
<script>
    window.onload = function(){
        var topDiv = document.querySelector('#top')
        var navDiv = document.querySelector('#nav')
        var h = topDiv.offsetHeight
        // onscroll  元素滚动时执行
        window.onscroll = function(){
            // window.pageYOffset 页面滚动的距离
            var scrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop || 0
            if (scrollY>h) {
                navDiv.className = 'nav'
            }else if(scrollY<h){
                navDiv.className = ''
            }
        }
    }
</script>
</html>